package com.pinecone.controller;

import com.pinecone.common.utils.R;
import com.pinecone.entity.LiveRecordEntity;
import com.pinecone.entity.LiveRecordTaskEntity;
import com.pinecone.entity.LiveRoomEntity;
import com.pinecone.service.LiveRecordService;
import com.pinecone.service.LiveRecordTaskService;
import com.pinecone.service.LiveRoomService;
import com.pinecone.service.TxVideoService;
import com.pinecone.service.impl.TxVideoServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 对接腾讯回调接口
 * Created by hushangjie on 2017/9/13.
 */
@RestController
public class TXVideoController {
    protected static final Logger logger = LoggerFactory.getLogger(TXVideoController.class);

    @Value("${txvideo.apikey}")
    private String apikey;
    @Value("${txvideo.appid}")
    private Integer appid;
    @Value("${txvideo.url}")
    private String txUrl;
    @Value("${txvideo.bizid}")
    private String bizid;

    @Autowired
    private TxVideoService txVideoService;
    @Autowired
    private LiveRoomService liveRoomService;
    @Autowired
    private LiveRecordService liveRecordService;
    @GetMapping("/test_get_flux")
    public R test2(){

        Calendar calendarStart = Calendar.getInstance();
        calendarStart.set(2017,9,14,0,0);

        Double sumFlux = txVideoService.getSumFlux("10930_GOLRToy1",calendarStart.getTime());
        return R.ok().put("总流量",sumFlux);

    }
    @GetMapping("/test_online")
    public R testOnlineAccount(){

        Calendar calendarStart = Calendar.getInstance();
        calendarStart.set(2017,9,15,0,0);

        txVideoService.setOnlineMaxNumber("10930_GOLRToy1",calendarStart.getTime());
        return R.ok().put("总流量","内部执行中");

    }

    /**
     * 接收腾讯云事件回调
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     */

    @PostMapping("/q_cloud/call_back")
    public R TXCallBack(@RequestBody Map<String, String> map) throws UnsupportedEncodingException, ParseException {
        System.out.println("==============");
        System.out.println(map);
        //0 — 断流； 1 — 推流；100 — 新的录制文件已生成；200 — 新的截图文件已生成
        if (map.get("event_type").toString().equals("0")){
            //断流了,更新直播间状态
            String streamId = map.get("stream_id").toString();
            String eventId = streamId.substring(streamId.indexOf("_")+1,streamId.length());
            LiveRoomEntity liveRoom = liveRoomService.queryObject(eventId);
            liveRoom.setLiveStatus(2);
            liveRoom.setEventEndTime(new Date());
            liveRoomService.update(liveRoom);
            logger.info("断流了"+streamId);
            //结束录制任务,腾讯云后台开启自动录制，则不需要手动录制
            if (liveRoom.isEnableRecord()){
                txVideoService.stopRecordTask(streamId);
            }
            //获取直播时间段内并发数，并记录到直播间
            txVideoService.setOnlineMaxNumber(streamId,new Date());
        }
        if (map.get("event_type").toString().equals("1")){
            //推流开始
            String streamId = map.get("stream_id").toString();
            String eventId = streamId.substring(streamId.indexOf("_")+1,streamId.length());
            LiveRoomEntity eventEntity = liveRoomService.queryObject(eventId);
            eventEntity.setLiveStatus(1);
            liveRoomService.update(eventEntity);
            logger.info("断流了"+streamId);
            //创建录制任务
            if (eventEntity.isEnableRecord()){
                txVideoService.createRecordTask(new Date(),bizid+"_"+eventEntity.getLiveRoomId());
            }

        }
        if (map.get("event_type").toString().equals("100") && map.get("video_url").contains("eof")){
            //录制文件生成，设置回看地址
            //如何解决中间断流，和视频合成的问题
            //录制文件生成回调会发送两次消息，一个是文件头信息，一次是分片信息，即后缀playlist.m3u8和palylist_eof.m3u8
            //我们只需要记录一个就行

            String streamId = map.get("stream_id").toString();
            String eventId = streamId.substring(streamId.indexOf("_")+1,streamId.length());
            //往录制表添加记录
            LiveRecordEntity liveRecordEntity = new LiveRecordEntity();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long startTime = Long.valueOf(map.get("start_time")) * 1000 ;
            long endTime = Long.valueOf(map.get("end_time")) * 1000 ;
            liveRecordEntity.setCreatTime(new Date())
                    .setDuration(map.get("duration").toString())
                    .setEndTime(new Date(endTime))
                    .setStartTime(new Date(startTime))
                    .setFileFormat(map.get("file_format"))
                    .setFileSize(map.get("file_size"))
                    .setLiveRoomId(eventId)
                    .setStreamId(streamId)
                    .setVideoId(map.get("video_id"))
                    .setFileId(map.get("file_id"))
                    .setVideoUrl(map.get("video_url"));
            liveRecordService.save(liveRecordEntity);
            logger.info("录制文件落地成功",streamId);
        }
        if (map.get("event_type").toString().equals("200")){
            //截图生成

        }
        return R.ok();
    }

    /**
     * 禁播
     * @param event_id
     * @return
     */
    @GetMapping("/live/forbid/{event_id}")
    public R changeLiveState(@PathVariable("event_id") String event_id){
        LiveRoomEntity eventEntity = liveRoomService.queryObject(event_id);
        txVideoService.switchLiveState(bizid+"_"+eventEntity.getLiveRoomId(),0);
        return R.ok();
    }

    /**
     * 断流
     * @param event_id
     * @return
     */
    @GetMapping("/live/break/{event_id}")
    public R breakLiveState(@PathVariable("event_id") String event_id){
        LiveRoomEntity eventEntity = liveRoomService.queryObject(event_id);
        txVideoService.switchLiveState(bizid+"_"+eventEntity.getLiveRoomId(),2);
        return R.ok();
    }

    /**
     * 允许继续推流
     * @param event_id
     * @return
     */
    @GetMapping("/live/carry/{event_id}")
    public R breakContinueState(@PathVariable("event_id") String event_id){
        LiveRoomEntity eventEntity = liveRoomService.queryObject(event_id);
        txVideoService.switchLiveState(bizid+"_"+eventEntity.getLiveRoomId(),1);
        return R.ok();
    }

    @GetMapping("/record")
    public R testRecord() throws UnsupportedEncodingException {
        txVideoService.createRecordTask(new Date(),bizid+"_"+"nsaAfDt8");
        return R.ok();
    }
    @GetMapping("/record_stop")
    public R testRecordStop() throws UnsupportedEncodingException {
        txVideoService.stopRecordTask(bizid+"_"+"nsaAfDt8");
        return R.ok();
    }
    //查询某个直播当前在线观看人数
    @GetMapping("/live/online_nums")
    public R getOnlineNumbers(@PathVariable(value = "room_id",required = true) String streamId){

        return R.ok();
    }
}
